package me.zhengjie.kwService.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.exception.ParameterException;
import me.zhengjie.kwService.StudentService;
import me.zhengjie.mapper.StudentMapper;
import me.zhengjie.pojo.entity.Student;
import me.zhengjie.util.AssertUtils;
import me.zhengjie.util.ruoyiexcel.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Long
 * @date 2021/6/28 12:17
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper,Student> implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public List<Student> selectList() {
        return studentMapper.selectList(null);
    }

    @Override
    public void saveImport(List<Student> students) {
        List<String> stringList = students.stream().map(Student::getIdCard)
                .collect(Collectors.toList());
        long count = stringList.stream().distinct().count();
        if (stringList.size() != count) {
            throw new ParameterException("存在重复身份证");
        }
        /*对导入的数据做初步判断是否存在重复数据*/
        students.forEach(student->{
            AssertUtils.isNotNull(student.getIdCard(),"身份证号不可为空");
            AssertUtils.isNotNull(student.getNameCn(),"姓名不可为空");
            AssertUtils.isNotNull(student.getStudentNumber(),"学号不可为空");
            AssertUtils.isNotNull(student.getPhone(),"手机号不可为空");
            AssertUtils.isMobile(student.getPhone(),student.getNameCn()+"的手机号格式不正确");
            AssertUtils.isIdCard(student.getIdCard(),student.getNameCn()+"的身份证号格式不正确");
        });

        students.forEach(s->{
            UpdateWrapper<Student> wrapper = new UpdateWrapper<>();
            wrapper.eq("id_card",s.getIdCard())
                    .set("student_number",s.getStudentNumber())
                    .set("name_cn",s.getNameCn())
                    .set("phone",s.getPhone())
                    .set(StringUtils.isNotBlank(s.getCollege()),"college",s.getCollege())
                    .set(StringUtils.isNotBlank(s.getClasses()),"classes",s.getClasses());
            saveOrUpdate(s,wrapper);
        });

    }
}
